import { NextRequest, NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';
import prisma from '@/lib/auth/prisma';

// 获取单个文档
export async function GET(req: NextRequest, { params }: { params: { id: string } }) {
  try {
    const token = await getToken({ req });
    if (!token?.id) {
      return NextResponse.json({ error: '未授权访问' }, { status: 401 });
    }

    // 处理新建文档的路由
    if (params.id === 'new') {
      return NextResponse.json({ title: '', content: '' });
    }

    const document = await prisma.document.findUnique({
      where: {
        id: params.id,
        authorId: token.id,
      },
    });

    if (!document) {
      return NextResponse.json({ error: '文档不存在' }, { status: 404 });
    }

    return NextResponse.json(document);
  } catch (error) {
    console.error('获取文档失败:', error);
    return NextResponse.json(
      { error: '获取文档失败' },
      { status: 500 }
    );
  }
}

// 更新文档
export async function PUT(req: NextRequest, { params }: { params: { id: string } }) {
  try {
    const token = await getToken({ req });
    if (!token?.id) {
      return NextResponse.json({ error: '未授权访问' }, { status: 401 });
    }

    const { title, content, published } = await req.json();

    if (!title || !content) {
      return NextResponse.json(
        { error: '标题和内容不能为空' },
        { status: 400 }
      );
    }

    // 验证文档所有权
    const existingDocument = await prisma.document.findUnique({
      where: {
        id: params.id,
        authorId: token.id,
      },
    });

    if (!existingDocument) {
      return NextResponse.json({ error: '文档不存在' }, { status: 404 });
    }

    const document = await prisma.document.update({
      where: {
        id: params.id
      },
      data: {
        title,
        content,
        published: published ?? existingDocument.published,
      },
    });

    return NextResponse.json(document);
  } catch (error) {
    console.error('更新文档失败:', error);
    return NextResponse.json(
      { error: '更新文档失败' },
      { status: 500 }
    );
  }
}

// 删除文档
export async function DELETE(req: NextRequest, { params }: { params: { id: string } }) {
  try {
    const token = await getToken({ req });
    if (!token?.id) {
      return NextResponse.json({ error: '未授权访问' }, { status: 401 });
    }

    const documentId = await Promise.resolve(params.id);

    // 验证文档所有权
    const document = await prisma.document.findUnique({
      where: {
        id: params.id,
        authorId: token.id,
      },
    });

    if (!document) {
      return NextResponse.json({ error: '文档不存在' }, { status: 404 });
    }

    await prisma.document.delete({
      where: {
        id: params.id
      },
    });

    return NextResponse.json({ message: '文档已删除' });
  } catch (error) {
    console.error('删除文档失败:', error);
    return NextResponse.json(
      { error: '删除文档失败' },
      { status: 500 }
    );
  }
}